
const xpath = '//h3[@class="tiktok-12ijsdd-H3CountInfos e1457k4r0"]//div[@class="tiktok-1kd69nj-DivNumber e1457k4r2"][2]//strong'
// const xpath = '//div[@class="tiktok-uha12h-DivContainer e1vl87hj1"]//img//@src'
// const xpath = `'https://www.tiktok.com'+//div[@class="tiktok-1mnwhn0-DivAuthorContainer etvrc4k6"]//a[@class="avatar-anchor tiktok-n64j3r etvrc4k4"]//@href`

function xpathToJq(xpath) {
    // 判定是否为http
    const httpRegex = /[a-zA-z]+:\/\/[^\s]*/
    if (xpath.match(httpRegex) && xpath.match(/\+/)) {
        // 获取 拼接字段
        let arr = xpath.split('+')
        return arr[0].substring(1,arr[0].length-1) + xpathToJq(arr[1])
    }
    // 用 // 切割数组
    const xpathArr = xpath.split("//")
    // console.log(xpathArr)
    // 遍历，正则匹配获取信息。 const regex = /^(\w+)\[@(\w+)="(.+)"\](?:\[(\d+)\])?$/;
    const regex = /^(\w+)(?:\[@(\w+)="(.+)"\])?(?:\[(\d+)\])?$/
    var jq = ""
    xpathArr.forEach((item, index) => {
        const itemArr = item.match(regex)
        console.log("itemArr ", index, itemArr)
        if (!itemArr) {
            return
        }
        var tag = itemArr?.[1]
        var prefix = itemArr?.[2] === 'class' ? '.' : (itemArr?.[2] === 'id' ? '#' : "")
        var name = itemArr?.[3]?.split(' ').map(item => prefix + item).join('') || ""
        var getIndex =  Number(itemArr?.[4])
        if (!jq) {
            jq = '$("' + tag + name + '")'
        }else if (tag) {
            jq = jq + '.find("' + tag + name + '")'
        }
        if (Number.isInteger(getIndex)) {
            jq = jq + '.eq(' + (getIndex - 1) + ')'
        }
    })
    if (xpathArr[xpathArr.length - 1][0] === '@') {
        jq += '.attr("' + xpathArr[xpathArr.length - 1].substring(1) + '")'
    } else {
        jq += '.clone().children().remove().end().text()'
    }
    return jq
}

console.log(xpathToJq(xpath))